<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>英雄</title>
    <style>
        table,
        td {
            border-collapse: collapse;
        }

        td {
            padding: 10px 20px;
        }
    </style>
</head>

<body>
    <div id="root"></div>

    <script src="../js/react.development.js"></script>
    <script src="../js/react-dom.development.js"></script>
    <script src="../js/babel.min.js"></script>

    <script type="text/babel">

        class Hero extends React.Component {
            state = {
                name: '',
                type: '',
                heros: [
                    { id: 1, name: '孙膑', type: '辅助' },
                    { id: 2, name: '小乔', type: '中单' },
                    { id: 3, name: '扁鹊', type: '法师' }
                ]
            }

            getData = (v) => {
                return e => {
                    this.setState({
                        [v]: e.target.value
                    })
                }
            }

            add = () => {
                //获取表单元素中的值
                //添加
                let obj = {name: this.state.name, type: this.state.type};
                obj.id = this.state.heros.length + 1;
                //生成一个新的 heros 数组
                let newArr = [obj,...this.state.heros];
                //更新
                this.setState({
                    heros: newArr,
                    name: '',
                    type: ''
                });
            }

            render() {
                return <div>
                    <input type="text" value={this.state.name} onChange={this.getData('name')} />
                    <input type="text" value={this.state.type} onChange={this.getData('type')} />
                    <button onClick={this.add}>添加</button>
                    <hr />

                    <table border="1">
                        <thead>
                            <tr><td>ID</td><td>名字</td><td>类型</td><td>测试</td></tr>
                        </thead>
                        <tbody>
                            {
                                this.state.heros.map((item, index) => {
                                    return <tr key={index}><td>{item.id}</td><td>{item.name}</td><td>{item.type}</td><td><input type="text"/></td></tr>
                                })
                            }
                        </tbody>
                    </table>
                </div>
            }
        }

        ReactDOM.render(<Hero />, document.querySelector("#root"));
    </script>
</body>

</html>